package com.jwaoo.chat.session.actions;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.dx.as.common.file.AttachmentStore;
import com.dx.as.common.storage.StorageType;
import com.dx.as.common.storage.StorageUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.common.sys.ScreenUtil;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.R;
import com.jwaoo.chat.bitmap.ImageUtil;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.pick.PickImageHelper;
import com.jwaoo.chat.session.pick.SendImageHelper;
import com.jwaoo.chat.session.pick.activity.PickImageActivity;
import com.jwaoo.chat.session.pick.activity.PreviewImageFromCameraActivity;
import com.jwaoo.media.video.helper.RequestCode;

import java.io.File;

/**
 * Created by zhoujianghua on 2015/7/31.
 */
public abstract class PickImageAction extends BaseAction {

    private static final int PICK_IMAGE_COUNT = 9;
    private static final int PORTRAIT_IMAGE_WIDTH = ScreenUtil.screenWidth;
    private static final int PORTRAIT_IMAGE_HEIGHT = ScreenUtil.screenHeight;

    public static final String MIME_JPEG = "image/jpeg";
    public static final String JPG = ".jpg";
    private int pick_image;
    private int preview_image_from_camera;
    private boolean multiSelect;
    private boolean crop = false;
    private int snap;
    protected abstract void onPicked(File file ,int snap);

    protected PickImageAction(int iconResId, int titleId, boolean multiSelect) {
        super(iconResId, titleId);
        this.multiSelect = multiSelect;
        if (this instanceof SnapChatAction){
            pick_image = RequestCode.PICK_IMAGE_SNAP;
            preview_image_from_camera = RequestCode.PREVIEW_IMAGE_FROM_CAMERA_SNAP;
        }else {
            pick_image = RequestCode.PICK_IMAGE;
            preview_image_from_camera = RequestCode.PREVIEW_IMAGE_FROM_CAMERA;
        }
    }

    @Override
    public void onClick() {
        int requestCode = pick_image;
        if (this instanceof SnapChatAction){
            getContainer().proxy.openSnapView();

            return;
        }
        showSelector(getTitleId(), requestCode, multiSelect, tempFile());
    }

    private String tempFile() {
        String filename = StringUtil.get32UUID() + JPG;
        return StorageUtil.getWritePath(filename, StorageType.TYPE_TEMP);
    }

    /**
     * 打开图片选择器
     */
    private void showSelector(int titleId, final int requestCode, final boolean multiSelect, final String outPath) {
        snap = ChatConstants.unsnap;
        PickImageHelper.PickImageOption option = getOption(titleId,requestCode,multiSelect,outPath);
        PickImageHelper.pickImage(getActivity(), requestCode, option);
    }

    private PickImageHelper.PickImageOption getOption(int titleId, final int requestCode, final boolean multiSelect, final String outPath){
        PickImageHelper.PickImageOption option = new PickImageHelper.PickImageOption();
        option.titleResId = titleId;
        option.multiSelect = multiSelect;
        option.multiSelectMaxCount = PICK_IMAGE_COUNT;
        option.crop = crop;
        option.cropOutputImageWidth = PORTRAIT_IMAGE_WIDTH;
        option.cropOutputImageHeight = PORTRAIT_IMAGE_HEIGHT;
        option.outputPath = outPath;
        return option;
    }

    public void pickFromCamrera(){
        snap = ChatConstants.snap;
        int requestCode = pick_image;
        PickImageHelper.PickImageOption option = getOption(getTitleId(),requestCode,multiSelect,tempFile());
        PickImageHelper.pickFromCamrera(getActivity(), requestCode, option);
    }
    public void pickFromLocal(){
        snap = ChatConstants.snap;
        int requestCode = pick_image;
        PickImageHelper.PickImageOption option = getOption(getTitleId(),requestCode,multiSelect,tempFile());
        PickImageHelper.pickFromLocal(getActivity(), requestCode, option);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == pick_image){
            onPickImageActivityResult(requestCode, data);
        }else if (requestCode == preview_image_from_camera){
            onPreviewImageActivityResult(requestCode, data);
        }
    }

    /**
     * 图片选取回调
     */
    private void onPickImageActivityResult(int requestCode, Intent data) {
        if (data == null) {
            Toast.makeText(getActivity(), R.string.picker_image_error, Toast.LENGTH_LONG).show();
            return;
        }
        boolean local = data.getBooleanExtra(Extras.EXTRA_FROM_LOCAL, false);
        if (local) {
            // 本地相册
            sendImageAfterSelfImagePicker(data);
        } else {
            // 拍照
            Intent intent = new Intent();
            if (!handleImagePath(intent, data)) {
                return;
            }

            intent.setClass(getActivity(), PreviewImageFromCameraActivity.class);
            getActivity().startActivityForResult(intent, preview_image_from_camera);
        }
    }

    /**
     * 是否可以获取图片
     */
    private boolean handleImagePath(Intent intent, Intent data) {
        String photoPath = data.getStringExtra(Extras.EXTRA_FILE_PATH);
        if (TextUtils.isEmpty(photoPath)) {
            Toast.makeText(getActivity(), R.string.picker_image_error, Toast.LENGTH_LONG).show();
            return false;
        }

        File imageFile = new File(photoPath);
        intent.putExtra("OrigImageFilePath", photoPath);
        File scaledImageFile = ImageUtil.getScaledImageFileWithMD5(imageFile, MIME_JPEG);

        boolean local = data.getExtras().getBoolean(Extras.EXTRA_FROM_LOCAL, true);
        if (!local) {
            // 删除拍照生成的临时文件
            AttachmentStore.delete(photoPath);
        }

        if (scaledImageFile == null) {
            Toast.makeText(getActivity(), R.string.picker_image_error, Toast.LENGTH_LONG).show();
            return false;
        } else {
            ImageUtil.makeThumbnail(getActivity(), scaledImageFile);
        }
        intent.putExtra("ImageFilePath", scaledImageFile.getAbsolutePath());
        return true;
    }

    /**
     * 从预览界面点击发送图片
     */
    private void sendImageAfterPreviewPhotoActivityResult(Intent data) {
        SendImageHelper.sendImageAfterPreviewPhotoActivityResult(data, new SendImageHelper.Callback() {

            @Override
            public void sendImage(File file, boolean isOrig) {
                onPicked(file,snap);
            }
        });
    }

    /**
     * 发送图片
     */
    private void sendImageAfterSelfImagePicker(final Intent data) {
        SendImageHelper.sendImageAfterSelfImagePicker(getActivity(), data, new SendImageHelper.Callback() {

            @Override
            public void sendImage(File file, boolean isOrig) {
                onPicked(file,snap);
            }
        });
    }

    /**
     * 拍摄回调
     */
    private void onPreviewImageActivityResult(int requestCode, Intent data) {
        if (data.getBooleanExtra(PreviewImageFromCameraActivity.RESULT_SEND, false)) {
            sendImageAfterPreviewPhotoActivityResult(data);
        } else if (data.getBooleanExtra(PreviewImageFromCameraActivity.RESULT_RETAKE, false)) {
            String filename = StringUtil.get32UUID() + JPG;
            String path = StorageUtil.getWritePath(filename, StorageType.TYPE_IMAGE);

            if (requestCode == preview_image_from_camera) {
                PickImageActivity.start(getActivity(), makeRequestCode(pick_image), PickImageActivity.FROM_CAMERA, path);
            }
        }
    }
}
